<template>
  <div>
    <TopFilter ref="searchOrdersPanel" :list="searchOrdersList" :cols="3" :rows="2" :label-width="90" @filterChange="changeHandle" @onCollapse="collapseHandle" />
    <FilterTable
      ref="table"
      columnsRef="finance_repairFinance_receivables_maintable"
      :columns="columns"
      :fetchapi="fetchApi"
      :params="fetchParams"
      selectionType="multiple"
      :datakey="'rows'"
      :onColumnsChange="columns => (this.columns = columns)"
      :onRowSelectChange="arr => (this.onChangeColumn = arr)"
    >
      <template slot="controls">
        <el-button type="primary" @click="openPayments">收 款</el-button>
        <el-button type="primary" @click="hanldeDebtPay">欠款收款</el-button>
        <!-- <el-button type="primary" :loading="batchCancelBtnLoading" :disabled="batchCancelBtnLoading" @click="handleCancelSettelement">取消收银</el-button> -->
        <el-button v-show="is_auth" type="primary" @click="openReduction">减 免</el-button>
        <el-button type="primary" @click="openWriteOff">销 账</el-button>
        <el-button type="primary" @click="exportExcelReceiveData">导 出</el-button>
      </template>
    </FilterTable>
    <BaseDialog :visible.sync="showReceiptsDetail" title="收款明细" width="800px" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <receiptsDetail ref="receiptsDetail" @close="closeReceiptsDetail" />
    </BaseDialog>
    <Drawer :visible.sync="visible_detail" title="明细" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <detail ref="detail" :detailData="detailData" @close="closeDetail" />
    </Drawer>
    <BaseDialog
      :visible.sync="showPayments"
      :title="selectOrderPayoff ? '取消收款' : '收款'"
      width="900px"
      destroyOnClose
      :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }"
    >
      <payments ref="payments" @close="closePayments" />
    </BaseDialog>
    <BaseDialog :visible.sync="showDebtPayments" title="欠款收款" width="900px" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <debtPayments ref="debtPayments" @close="closeDebtPayments" />
    </BaseDialog>
    <BaseDialog :visible.sync="showReduction" title="减免" width="900px" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <reduction ref="reduction" @close="closeReduction" />
    </BaseDialog>
    <BaseDialog :visible.sync="showWriteOff" title="销账" width="900px" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <writeOff ref="writeOff" @close="closeWriteOff" />
    </BaseDialog>
  </div>
</template>

<script>
import moment from 'moment';
import dictCode from '@/utils/dictCode';
import { searchRoleByCode } from '@/api/common/empSelect/index';
import { dictionary } from '@/utils/dictMixin';
import receiptsDetail from './receiptsDetail';
import { exportExcelFile } from '@/utils/index';
import { getJxsSelect, getOrderList, getReceiveDetail, getRepairType, exportExcelData, batchCancelCollection } from '@/api/finance/repair/receivables';
import { getAllUser } from '@/api/finance/advancesReceived/register';
import detail from '@/pages/finance/repairFinance/receivables/detail';
import payments from '@/pages/finance/repairFinance/receivables/payments';
import debtPayments from './debtPayments';
import reduction from '@/pages/finance/repairFinance/receivables/reduction';
import writeOff from '@/pages/finance/repairFinance/receivables/writeOff';
import { isAuthorized } from '@/utils/index';
export default {
  name: 'Receivables',
  components: {
    receiptsDetail,
    detail,
    payments,
    reduction,
    writeOff,
    debtPayments
  },
  mixins: [dictionary],
  data() {
    // this.dmsFunc = { dmsFuncId: 55100010 };
    return {
      searchOrdersList: this.createSearchOrdersList(),
      columns: this.createTableColumns(),
      fetchParams: { xhrAbort: true },
      fetchApi: getOrderList,
      onChangeColumn: [],
      visible_detail: false,
      showReceiptsDetail: false,
      showPayments: false,
      showReduction: false,
      showWriteOff: false,
      // 是否可以减免
      is_auth: false,
      detailData: {},
      showDebtPayments: false, // 是否显示欠款结算弹窗
      batchCancelBtnLoading: false,
      selectOrderPayoff: false // 选择的收费对象是否结清
    };
  },

  computed: {},
  watch: {},
  mounted() {
    // this.getJxsSelect();
    this.getRepairType(); // 维修类型下拉
    this.serviceConsultant(); // 服务顾问下拉
    // 权限
    this.getAuth();
  },
  methods: {
    getAuth() {
      // 是否可减免的权限
      if (isAuthorized('1314', '13141005')) {
        this.is_auth = true;
      } else {
        this.is_auth = false;
      }
    },
    createSearchOrdersList() {
      return [
        {
          type: 'INPUT',
          label: '工单号',
          fieldName: 'roNo'
        },
        {
          type: 'SELECT',
          label: '是否结清',
          fieldName: 'payOff',
          itemList: this.createDictList('1004'),
          initialValue: 10041002
        },
        {
          type: 'INPUT',
          label: '车主',
          fieldName: 'ownerName'
        },
        {
          type: 'INPUT',
          label: '收费对象代码',
          fieldName: 'paymentObjectCode'
        },
        {
          type: 'INPUT',
          label: '备件销售单号',
          fieldName: 'salesPartNo'
        },
        {
          type: 'SELECT',
          label: '是否关单',
          fieldName: 'balanceClose',
          itemList: this.createDictList('1004')
        },
        {
          type: 'SELECT',
          label: '是否欠款结算',
          fieldName: 'arrBalance',
          itemList: this.createDictList('1004')
        },
        {
          type: 'INPUT',
          label: '车牌号',
          fieldName: 'license'
        },
        {
          type: 'INPUT',
          label: '收费对象名称',
          fieldName: 'paymentObjectName'
        },
        {
          type: 'INPUT',
          label: '担保方',
          fieldName: 'guarantor'
        },
        {
          type: 'INPUT',
          label: '结算单号',
          fieldName: 'balanceNo'
        },
        {
          type: 'SELECT',
          label: '已全部开票',
          fieldName: 'isAllInvoice',
          itemList: this.createDictList('1004')
        },
        {
          type: 'SELECT',
          label: '服务顾问',
          fieldName: 'serviceAdvisor',
          itemList: []
        },
        // {
        //   type: 'SELECT',
        //   label: '工单类型',
        //   fieldName: 'roType',
        //   itemList: this.createDictList('8068')
        // },
        {
          type: 'RANGE_DATE',
          label: '结算日期',
          style: { minWidth: '200px' },
          fieldName: 'balanceTimeBegin|balanceTimeEnd'
        },
        {
          type: 'RANGE_DATE',
          label: '结清日期',
          style: { minWidth: '200px' },
          fieldName: 'squareDateBegin|squareDateEnd'
        },
        {
          type: 'RANGE_DATE',
          label: '关单日期',
          style: { minWidth: '200px' },
          fieldName: 'balanceCloseTimeBegin|balanceCloseTimeEnd'
        },
        {
          type: 'SELECT',
          label: '维修类型',
          fieldName: 'repairTypeCode',
          itemList: []
        }
      ];
    },
    createTableColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 110,
          fixed: 'left',
          render: props => {
            return (
              <div>
                <el-button size="mini" type="text" onClick={() => this.openReceiptsDetail(props.row)}>
                  收款明细
                </el-button>
                <el-button size="mini" type="text" onClick={() => this.openDetail(props.row)}>
                  明细
                </el-button>
              </div>
            );
          }
          // <el-divider direction="vertical" />
          // <el-button size="mini" type="text" onClick={()=>this.detail(props.row)}>
          //   明细
          // </el-button>
          // <el-divider direction="vertical" />
          // <el-button size="mini" type="text" disabled={props.row.lockFlag === 10041002} onClick={()=>this.removelock(props.row.employeeId)}>
          //   解锁
          // </el-button>
          // <el-divider direction="vertical" />
          // <el-button size="mini" type="text" disabled={props.row.lockFlag === 10041001} onClick={()=>this.lock(props.row.employeeId)}>
          //   锁定
          // </el-button>
        },
        {
          title: '是否关单',
          dataIndex: 'BALANCE_CLOSE',
          sorter: true,
          render: props => {
            return <span>{this.createDictText(props.row.BALANCE_CLOSE, '1004')}</span>;
          }
        },
        {
          title: '是否欠款结算',
          dataIndex: 'ARR_BALANCE',
          sorter: true,
          render: props => {
            return <span>{this.createDictText(props.row.ARR_BALANCE, '1004')}</span>;
          }
        },
        {
          title: '结算单号',
          dataIndex: 'BALANCE_NO',
          sorter: true
        },
        // {
        //   title: '工单类型',
        //   dataIndex: 'RO_TYPE',
        //   sorter: true,
        //   render: props => {
        //     return <span>{this.createDictText(props.row.RO_TYPE, '8068')}</span>;
        //   }
        // },
        {
          title: '结算时间',
          dataIndex: 'BALANCE_TIME',
          sorter: true,
          dateFormat: 'yyyy-MM-dd HH:mm:ss',
          showOverflowTooltip: true
        },
        {
          title: '结清时间',
          dataIndex: 'SQUARE_DATE',
          sorter: true,
          dateFormat: 'yyyy-MM-dd HH:mm:ss',
          showOverflowTooltip: true
        },
        {
          title: '关单日期',
          dataIndex: 'BALANCE_CLOSE_TIME',
          sorter: true,
          dateFormat: 'yyyy-MM-dd HH:mm:ss',
          showOverflowTooltip: true
        },
        {
          title: '收费对象代码',
          dataIndex: 'PAYMENT_OBJECT_CODE',
          sorter: true
        },
        {
          title: '收费对象名称',
          dataIndex: 'PAYMENT_OBJECT_NAME',
          showOverflowTooltip: true,
          sorter: true
        },
        {
          title: '担保方',
          dataIndex: 'GUARANTOR',
          filter: true,
          filterType: 'input',
          showOverflowTooltip: true,
          sorter: true
        },
        {
          title: '应收账款',
          dataIndex: 'RECEIVABLE_AMOUNT',
          precision: 2,
          numberFormat: true,
          sorter: true
        },
        {
          title: '已收账款',
          dataIndex: 'RECEIVED_AMOUNT',
          precision: 2,
          sorter: true
        },
        {
          title: '已免账款',
          dataIndex: 'DERATED_AMOUNT',
          precision: 2,
          sorter: true
        },
        {
          title: '未收账款',
          dataIndex: 'NOT_RECEIVED_AMOUNT',
          precision: 2,
          sorter: true
        },
        {
          title: '已全部开票',
          dataIndex: 'IS_ALL_INVOICE',
          sorter: true,
          render: props => {
            return <span>{this.createDictText(props.row.IS_ALL_INVOICE, '1004')}</span>;
          }
        },
        {
          title: '是否结清',
          dataIndex: 'PAY_OFF',
          sorter: true,
          render: props => {
            return <span>{this.createDictText(props.row.PAY_OFF, '1004')}</span>;
          }
        },
        {
          title: '工单号',
          dataIndex: 'RO_NO',
          sorter: true,
          width: 120,
          showOverflowTooltip: true
        },
        {
          title: '备件销售单号',
          dataIndex: 'SALES_PART_NO',
          sorter: true
        },
        {
          title: '服务顾问',
          dataIndex: 'SERVICE_ADVISOR',
          sorter: true,
          editable: false,
          editType: 'select',
          editItems: []
        },
        {
          title: '车主编号',
          dataIndex: 'OWNER_NO',
          sorter: true
        },
        {
          title: '车主',
          dataIndex: 'OWNER_NAME',
          sorter: true,
          showOverflowTooltip: true
        },
        {
          title: '车牌号',
          dataIndex: 'LICENSE',
          sorter: true
        },
        {
          title: 'VIN',
          dataIndex: 'VIN',
          width: 150,
          sorter: true
        },
        {
          title: '维修类型',
          dataIndex: 'REPAIR_TYPE_CODE',
          sorter: true,
          editable: false,
          editType: 'select',
          editItems: []
        }
      ];
    },
    collapseHandle() {
      this.$nextTick(() => {
        this.$refs.table.$refs.pageTable.EXECUTE_RESET_HEIGHT();
      });
    },
    async getJxsSelect() {
      const res = await getJxsSelect();
      // console.log(res)
      this.searchOrdersList.find(item => item.fieldName === 'dealerCode').itemList = res.map(x => ({ value: x.DEALER_CODE, text: x.ASC_SHORTNAME }));
    },
    async getReceiveDetail(id) {
      const res = await getReceiveDetail(id);
      // console.log(res,'结清')
      this.showWriteOff = true;
      this.$nextTick(() => {
        this.$refs.writeOff.openModel(this.onChangeColumn, res.data);
      });
    },
    async serviceConsultant() {
      let testDrive = { role: dictCode.SERVICE_CONSULTANT };
      const res = await searchRoleByCode(testDrive);
      // console.log(res, '服务顾问');
      this.columns.find(item => item.dataIndex === 'SERVICE_ADVISOR').editItems = this.searchOrdersList.find(item => item.fieldName === 'serviceAdvisor').itemList = res.data.map(x => ({
        text: x.employeeName,
        value: x.userId + ''
      }));
    },
    async getRepairType() {
      const res = await getRepairType();
      this.searchOrdersList.find(item => item.fieldName === 'repairTypeCode').itemList = this.columns.find(x => x.dataIndex === 'REPAIR_TYPE_CODE').editItems = res.data.map(x => ({
        value: x.REPAIR_TYPE_CODE,
        text: x.REPAIR_TYPE_NAME
      }));
    },
    reset() {
      this.$refs.searchOrdersPanel.RESET_FORM();
      this.getOrderList();
    },
    changeHandle(val) {
      this.fetchParams = Object.assign({}, val);
    },
    openReceiptsDetail(data) {
      // console.log(data)
      // console.log(data.BALA_PAYOBJ_ID)
      // console.log(data.BALANCE_NO)
      this.showReceiptsDetail = true;
      this.$nextTick(() => {
        this.$refs.receiptsDetail.openModel(data);
      });
    },
    closeReceiptsDetail() {
      this.showReceiptsDetail = false;
    },
    openDetail(data) {
      this.detailData = data;
      this.visible_detail = true;
      /* this.$nextTick(()=>{
        // console.log(this.$refs.detail)
        this.$refs.detail.openModel(data)
      }) */

      // setTimeout(() => {
      //   // console.log(this.$refs.detail)
      //   this.$refs.detail.openModel(data);
      // }, 300);
    },
    closeDetail() {
      this.visible_detail = false;
    },
    // 点击收款
    openPayments(data) {
      console.log('select', this.onChangeColumn);
      if (this.onChangeColumn.length > 0) {
        let flag = true;
        for (let i = 0; i < this.onChangeColumn.length; i++) {
          if (this.onChangeColumn[i].PAYMENT_OBJECT_CODE != this.onChangeColumn[0].PAYMENT_OBJECT_CODE) {
            flag = false;
          }
        }
        if (flag) {
          this.showPayments = true;
          let isPayOff = false; // 是否结清（结清显示取消结算）
          this.onChangeColumn.map(item => {
            item.PAY_OFF == 10041001 && (isPayOff = true);
          });
          this.selectOrderPayoff = isPayOff;
          this.$nextTick(() => {
            this.$refs.payments.openModel(this.onChangeColumn);
          });
        } else {
          this.$notify.error({ title: '提示信息', message: '此操作必须选择同一收费对象' });
        }
      } else {
        this.$notify.info({ title: '提示信息', message: '请选择表格数据' });
      }
    },
    // 点击欠款收款
    hanldeDebtPay() {
      if (this.onChangeColumn.length > 0) {
        let flag = true; // 是否为同一收费对象
        let minusAmountOrderList = []; // 收款金额为负的行项
        let payOffOrderList = []; // 结清的行项
        let closeOrderList = []; // 已关单的行项
        let debtOrderList = []; // 已欠账行项
        for (let i = 0; i < this.onChangeColumn.length; i++) {
          let item = this.onChangeColumn[i];
          if (item.PAYMENT_OBJECT_CODE != this.onChangeColumn[0].PAYMENT_OBJECT_CODE) {
            flag = false;
          }
          item.NOT_RECEIVED_AMOUNT < 0 && minusAmountOrderList.push(item.BALANCE_NO);
          item.PAY_OFF == 10041001 && payOffOrderList.push(item.BALANCE_NO);
          item.BALANCE_CLOSE == 10041001 && closeOrderList.push(item.BALANCE_NO);
          item.ARR_BALANCE == 10041001 && debtOrderList.push(item.BALANCE_NO);
        }
        console.log(minusAmountOrderList, payOffOrderList, closeOrderList, debtOrderList, '不符合规则的行项');
        if (flag) {
          if (minusAmountOrderList.length) return this.$notify.warning({ title: '提示信息', message: `结算单${minusAmountOrderList.join(',')}未收账款为负不能欠款收款` });
          if (payOffOrderList.length) return this.$notify.warning({ title: '提示信息', message: `结算单${payOffOrderList.join(',')}已结清不能欠款收款` });
          if (closeOrderList.length) return this.$notify.warning({ title: '提示信息', message: `结算单${closeOrderList.join(',')}已关单不能欠款收款` });
          if (debtOrderList.length) return this.$notify.warning({ title: '提示信息', message: `结算单${debtOrderList.join(',')}已欠款不能再次欠款收款` });
          this.showDebtPayments = true;
          this.$nextTick(() => {
            this.$refs.debtPayments.openModel(this.onChangeColumn);
          });
        } else {
          this.$notify.error({ title: '提示信息', message: '此操作必须选择同一收费对象' });
        }
      } else {
        this.$notify.warning({ title: '提示信息', message: '请选择一条记录' });
      }
    },
    closePayments(val) {
      console.log('是否重置:' + !val);
      if (!val) {
        this.fetchParams = { ...this.fetchParams };
      }
      this.showPayments = false;
    },
    closeDebtPayments(val) {
      if (!val) {
        this.fetchParams.xhrAbort = true;
        this.fetchParams = { ...this.fetchParams, xhrAbort: false };
      }
      this.showDebtPayments = false;
    },
    openReduction(data) {
      console.log('select', this.onChangeColumn);
      if (this.onChangeColumn.length > 0) {
        let flag = true;
        for (let i = 0; i < this.onChangeColumn.length; i++) {
          if (this.onChangeColumn[i].PAYMENT_OBJECT_CODE != this.onChangeColumn[0].PAYMENT_OBJECT_CODE) {
            flag = false;
          }
        }
        if (flag) {
          this.showReduction = true;
          this.$nextTick(() => {
            this.$refs.reduction.openModel(this.onChangeColumn);
          });
        } else {
          this.$notify.error({ title: '提示信息', message: '此操作必须选择同一收费对象' });
        }
      } else {
        this.$notify.info({ title: '提示信息', message: '请选择表格数据' });
      }
    },
    // 点击取消收银 hxj 2020.6.11 0元工单取消逻辑由单独按钮变为自动取消
    async handleCancelSettelement() {
      let unclearOrderList = []; // 未结清列表
      if (this.onChangeColumn.length) {
        for (let i = 0; i < this.onChangeColumn.length; i++) {
          let item = this.onChangeColumn[i];
          item.PAY_OFF != 10041001 && unclearOrderList.push(item.BALANCE_NO);
        }
        if (unclearOrderList.length) return this.$notify.warning({ title: '提示信息', message: `结算单${unclearOrderList.join(',')}未结清不能取消收款` });
        // 取消收银接口
        let balanceNumberList = this.onChangeColumn.map(item => item.BALANCE_NO);
        this.batchCancelBtnLoading = true;
        try {
          let res = await batchCancelCollection({
            balanceNumbers: balanceNumberList
          });
          if (res.resultCode == 200) {
            this.$notify.success({ title: '提示信息', message: '取消收款成功' });
            // 重新查询列表数据
            this.fetchParams.xhrAbort = true;
            this.fetchParams = Object.assign({}, this.fetchParams, { xhrAbort: false });
          }
        } catch (err) {
          console.log(err, '批量取消收款失败');
        } finally {
          this.batchCancelBtnLoading = false;
        }
      } else {
        this.$notify.warning({ title: '提示信息', message: '请选择一条记录' });
      }
    },
    closeReduction(val) {
      if (!val) {
        this.fetchParams = { ...this.fetchParams };
      }
      this.showReduction = false;
    },
    openWriteOff(data) {
      console.log('select', this.onChangeColumn);
      if (this.onChangeColumn.length == 1) {
        // console.log('key',this.onChangeColumn[0].BALA_PAYOBJ_ID)
        this.getReceiveDetail(this.onChangeColumn[0].BALA_PAYOBJ_ID);
      } else {
        this.$notify.error({ title: '提示信息', message: '请选择一条表格数据' });
      }
    },
    closeWriteOff(val) {
      if (!val) {
        this.fetchParams = { ...this.fetchParams };
      }
      this.showWriteOff = false;
    },
    exportExcelReceiveData() {
      exportExcelData(this.fetchParams).then(res => {
        console.log(res);
        exportExcelFile(res, '维修收款');
      });
    }
  }
};
</script>

<style lang="less" scoped>
.vehicle-details-wrap {
  position: relative;
  padding-bottom: @modulePadding;
  .box {
    border: 1px solid #ccc;
    padding-top: 15px;
    padding-bottom: 15px;
    padding-right: 15px;
    border-radius: @borderRadius;
    margin-bottom: 20px;
    box-shadow: @boxShadow;
    display: flex;
    flex-direction: column;
    .el-row {
      text-align: center;
    }
  }
  .left {
    position: absolute;
    left: 0;
    width: calc(100% - 300px);
    border: 1px solid @borderColor;
    border-radius: @borderRadius;
    box-shadow: @boxShadow;
    padding: @modulePadding;
    padding-left: 0;
  }
  .right {
    margin-left: calc(100% - 280px);
    border: 1px solid @borderColor;
    border-radius: @borderRadius;
    box-shadow: @boxShadow;
    padding: @modulePadding;
  }
  .choose-style {
    color: @primaryColor;
  }
}
</style>
